{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>\n",
       ".cell-output-ipywidget-background {\n",
       "    background-color: transparent !important;\n",
       "}\n",
       ":root {\n",
       "    --jp-widgets-color: var(--vscode-editor-foreground);\n",
       "    --jp-widgets-font-size: var(--vscode-editor-font-size);\n",
       "}  \n",
       "</style>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%html\n",
    "<style>\n",
    ".cell-output-ipywidget-background {\n",
    "    background-color: transparent !important;\n",
    "}\n",
    ":root {\n",
    "    --jp-widgets-color: var(--vscode-editor-foreground);\n",
    "    --jp-widgets-font-size: var(--vscode-editor-font-size);\n",
    "}  \n",
    "</style>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import json\n",
    "import random\n",
    "import re\n",
    "from typing import TypedDict\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "import art\n",
    "from art.local import LocalBackend\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "\n",
    "class TemporalCluePuzzle(TypedDict):\n",
    "    num_clues: int\n",
    "    prompt: str\n",
    "    solution: dict[str, str]\n",
    "\n",
    "\n",
    "puzzles_path = \"../data/temporal-clue/puzzles.json\"\n",
    "puzzles: list[TemporalCluePuzzle] = json.loads(open(puzzles_path).read())\n",
    "val_puzzles = puzzles[:64]\n",
    "test_puzzles = puzzles[64:128]\n",
    "train_puzzles = puzzles[128:]\n",
    "random.seed(42)\n",
    "random.shuffle(train_puzzles)\n",
    "\n",
    "\n",
    "async def rollout(model: art.Model, puzzle: TemporalCluePuzzle) -> art.Trajectory:\n",
    "    messages: art.Messages = [\n",
    "        {\"role\": \"user\", \"content\": puzzle[\"prompt\"] + \" /no_think\"}\n",
    "    ]\n",
    "    client = model.openai_client()\n",
    "    chat_completion = await client.chat.completions.create(\n",
    "        messages=messages, model=model.name, max_tokens=4096\n",
    "    )\n",
    "    choice = chat_completion.choices[0]\n",
    "    content = choice.message.content\n",
    "    assert isinstance(content, str)\n",
    "    num_correct = 0\n",
    "    for key, value in puzzle[\"solution\"].items():\n",
    "        if matches := re.findall(rf\"{key}\\. ([A-Za-z \\.:-]+)\", content):\n",
    "            match = matches[-1]\n",
    "            if match.strip().lower() == value.lower():\n",
    "                num_correct += 1\n",
    "    reward = acc = num_correct / len(puzzle[\"solution\"])\n",
    "    return art.Trajectory(\n",
    "        messages_and_choices=[*messages, choice], reward=reward, metrics={\"acc\": acc}\n",
    "    )\n",
    "\n",
    "\n",
    "model = art.TrainableModel(\n",
    "    name=\"056\", project=\"temporal-clue\", base_model=\"Qwen/Qwen2.5-7B-Instruct\"\n",
    ")\n",
    "backend = LocalBackend()\n",
    "await model.register(backend)\n",
    "\n",
    "stride = 8\n",
    "\n",
    "unstarted = list(\n",
    "    art.gather_trajectory_groups(\n",
    "        (\n",
    "            art.TrajectoryGroup(rollout(model, puzzle) for _ in range(16))\n",
    "            for puzzle in train_puzzles[i * stride : (i + 1) * stride]\n",
    "        ),\n",
    "        pbar_desc=f\"batch: {i}\",\n",
    "    )\n",
    "    for i in range(await model.get_step(), len(train_puzzles) // stride)\n",
    ")\n",
    "pending: set[asyncio.Task[list[art.TrajectoryGroup]]] = set()\n",
    "max_pending = 2\n",
    "\n",
    "\n",
    "def queue_batches() -> None:\n",
    "    while len(pending) < max_pending and unstarted:\n",
    "        pending.add(asyncio.create_task(unstarted.pop(0)))\n",
    "\n",
    "\n",
    "queue_batches()\n",
    "while pending:\n",
    "    done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)\n",
    "    queue_batches()\n",
    "    for task in done:\n",
    "        if await model.get_step() % 5 == 0:\n",
    "            val_groups = await art.gather_trajectory_groups(\n",
    "                (\n",
    "                    art.TrajectoryGroup(rollout(model, puzzle) for _ in range(1))\n",
    "                    for puzzle in val_puzzles\n",
    "                ),\n",
    "                pbar_desc=\"val\",\n",
    "                pbar_total_completion_tokens=False,\n",
    "            )\n",
    "            await model.log(val_groups)\n",
    "            queue_batches()\n",
    "        train_groups = task.result()\n",
    "        for group in train_groups:\n",
    "            max_reward = max(trajectory.reward for trajectory in group)\n",
    "            for trajectory in group:\n",
    "                trajectory.metrics[\"max_reward\"] = max_reward\n",
    "        await model.delete_checkpoints()\n",
    "        await model.train(\n",
    "            train_groups,\n",
    "            config=art.TrainConfig(learning_rate=5e-6),\n",
    "            _config=art.dev.TrainConfig(precalculate_logprobs=True),\n",
    "        )"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
